<!-- 新增或编辑流程配置 -->
<template>
  <div class="add_or_edit_process">
    <Row v-show="editFlag">
      <Col span="24" class="tips">
        <Icon type="md-alert" class="tips_icon" />
        提示：编辑后的数据仅对新发起的流程生效
      </Col>
    </Row>
    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="100"
      label-position="left">
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="公司范围：" prop="companyId">
            <tree_select
              v-model="formValidate.companyId"
              ref="areaTree"
              :treeList="companyList"
              selectPlaceholder="请选择"
              :maxTagCount="3"
              :saveParent="true"></tree_select>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div class="process_node">
      <Row class="process_node_title">
        <Col span="8">
          <span class="title_text">流程配置</span>
        </Col>
        <Col span="4" offset="12">
          <Button type="primary" @click="addNode" icon="ios-add">添加审核节点</Button>
        </Col>
      </Row>
      <Table ref="table" border :columns="columns" :data="tableList" height="400" class="table_node">
        <!-- 审核人类型 -->
        <template slot-scope="{ row }" slot="reviewerType">
          <Select
            v-model="row.reviewerType"
            placeholder="请选择审核人类型"
            @on-change="
              (e) => {
                return reviewerTypeChange(row)
              }
            "
            transfer>
            <Option
              v-for="option in reviewerTypeList"
              :value="option.key"
              :key="option.key"
              :label="option.vlaue"></Option>
          </Select>
        </template>
        <!-- 审核人类型 -->
        <template slot-scope="{ row }" slot="reviewerId">
          <div v-if="row.reviewerType">
            <div v-if="row.reviewerType == '1'">
              <Select
                v-model="row.reviewerId"
                placeholder="请选择角色"
                multiple
                :max-tag-count="3"
                @on-change="
                  (e) => {
                    return roleNameChange(row, e)
                  }
                "
                :disabled="!row.reviewerType"
                transfer
                :label-in-value="true">
                <Option
                  v-for="option in roleIdsAttrSort"
                  :value="option.roleId"
                  :key="option.roleId"
                  :label="option.roleName"></Option>
              </Select>
            </div>
            <div v-else>
              <Select
                :disabled="!row.reviewerType"
                v-model="row.reviewerId"
                filterable
                multiple
                @on-query-change="searchUser"
                :label-in-value="true"
                @on-change="
                  (e) => {
                    return roleNameChange(row, e)
                  }
                "
                placeholder="请输入工号匹配人员"
                :max-tag-count="3"
                transfer>
                <Option
                  v-for="option in userList"
                  :value="option.workNo"
                  :key="option.workNo"
                  :label="option.userName"></Option>
              </Select>
            </div>
          </div>
          <div v-else>
            <span></span>
          </div>
        </template>
      </Table>
    </div>
    <div class="flex flex-horizontal-end btn-operate">
      <Button @click="AllModalCancel">关闭</Button>
      <Button type="primary" @click="submitFun()" style="margin-left: 8px">保存</Button>
    </div>
  </div>
</template>
<script>
  import tree_select from '@/components/tree_select.vue'
  import columnsAll from '../opt/columns.js'
  import processApi from '@/biz/flowApproval/processManagement'
  import teamsApi from '@/biz/buildingManagement/teams'
  import calc from '../opt/calc.js'
  export default {
    components: {
      tree_select
    },
    props: {
      processNo: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        formValidate: {
          companyId: []
        },
        ruleValidate: {
          companyId: [
            {
              required: true,
              type: 'array',
              message: '请选择公司范围',
              trigger: 'blur,change'
            }
          ]
        },
        companyList: [],
        columns: [],
        tableList: [
          {
            reviewerType: 1,
            reviewerId: [],
            reviewerDesc: ''
          }
        ],
        reviewerTypeList: [],
        roleIdsAttrSort: [],
        userList: [],
        editInfo: {},
        editFlag: false
      }
    },
    methods: {
      //获取业务组织架构
      getBusinessList(data) {
        processApi.getBusinessOrganTree().then((res) => {
          console.log(res, 'res')
          if (data) {
            let companyIdTmp = data.companyId.split(',')
            res &&
              res.forEach((item) => {
                if (companyIdTmp && companyIdTmp.includes(String(item.id))) {
                  item.checked = true
                }
                item.children.forEach((itemC) => {
                  if (companyIdTmp && companyIdTmp.includes(String(itemC.id))) {
                    itemC.checked = true
                  }
                  itemC.children.forEach((itemL) => {
                    if (companyIdTmp && companyIdTmp.includes(String(itemL.id))) {
                      itemL.checked = true
                    }
                  })
                })
              })
          }
          this.companyList = res
        })
      },
      //改变审核人类型
      reviewerTypeChange(data) {
        data.reviewerId = ''
        calc.syncData(this.tableList, data._index, data)
      },
      roleNameChange(data, obj) {
        calc.syncData(this.tableList, data._index, data, obj)
      },
      //根据工号查人员
      searchUser(filterTxt) {
        if (!filterTxt) {
          this.formValidate.userName = ''
          this.formValidate.workNo = ''
          return false
        }
        if (filterTxt.length < 5 || filterTxt.length > 8) {
          return false
        }
        teamsApi
          .getByWorkNo({
            workNo: filterTxt
          })
          .then((res) => {
            this.userList = calc.RemoveSameItem(this.userList, res, 'workNo')
          })
      },
      //获取前台角色
      getFrontRoleinit() {
        processApi.getAllRoleNameList().then((res) => {
          res &&
            res.forEach((item) => {
              item.roleId = String(item.roleId)
            })
          this.roleIdsAttrSort = res
        })
      },
      //添加审核节点
      addNode() {
        let dataNode = {
          reviewerType: 1,
          reviewerId: [],
          reviewerDesc: '',
          _index: this.tableList.length
        }
        this.tableList.push(dataNode)
        this.columns = columnsAll.processNodeColumns(this, this.tableList.length)
      },
      //删除
      delete(row) {
        let index = row._index
        if (index >= 0) this.tableList.splice(index, 1)
        this.columns = columnsAll.processNodeColumns(this, this.tableList.length)
      },
      // 上移
      upItems(index) {
        let update = this.tableList[index - 1]
        this.tableList.splice(index - 1, 1)
        this.tableList.splice(index, 0, update)
      },
      // 下移
      downItems(index) {
        let downdate = this.tableList[index + 1]
        this.tableList.splice(index + 1, 1)
        this.tableList.splice(index, 0, downdate)
      },
      AllModalCancel() {
        this.$Modal.confirm({
          title: '请确认',
          content: '关闭后数据将不做保存，是否确认关闭流程配置？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            this.$emit('onClose')
          }
        })
      },
      edit(data) {
        this.editFlag = true
        this.editInfo = {
          ...data
        }
        this.$nextTick(() => {
          this.userList = this.$tool.noRepeatObj(data.userList, 'workNo')
          this.tableList = this.$tool.deepClone(data.processDataList)
          this.columns = columnsAll.processNodeColumns(this, this.tableList.length)
          this.getBusinessList(data)
        })
      },
      submitFun() {
        let tableListflag = true
        this.tableList.some((item) => {
          let message = ''
          if (!item.reviewerType) {
            message = '审核人类型为必填项，请填写后重试!'
            tableListflag = false
            return this.$Message.error(message)
          }
          if (!item.reviewerId) {
            message = '审核人为必填项，请填写后重试!'
            tableListflag = false
            return this.$Message.error(message)
          }
        })
        this.$refs.formValidate.validate((valid) => {
          if (valid && tableListflag) {
            let params = {
              companyList: calc.BusinessOrganflatten(this.companyList, this.formValidate.companyId),
              processDataList: calc.formatProcessDataList(this.tableList),
              processNo: this.processNo
            }
            if (this.editFlag) {
              params.id = this.editInfo.id
              processApi.detailUpdate(params).then((res) => {
                this.$emit('onChangeTable')
              })
            } else {
              processApi.detailSave(params).then((res) => {
                this.$emit('onChangeTable')
              })
            }
          }
        })
      }
    },
    mounted() {
      this.columns = columnsAll.processNodeColumns(this, this.tableList.length)
      this.reviewerTypeList = columnsAll.reviewerTypeList()
      this.getBusinessList()
      this.getFrontRoleinit()
    }
  }
</script>
<style lang="scss" scoped>
  .add_or_edit_process {
    padding: 0 15px;

    .process_node {
      .title_text {
        font-size: 16px;
        line-height: 32px;
      }

      .table_node {
        margin: 10px 0;
      }
    }

    .tips {
      text-align: center;
      margin-bottom: 15px;
      background-color: rgba(254, 252, 236, 1);
      width: auto;
      line-height: 32px;

      .tips_icon {
        font-size: 20px;
        color: #0f42a7;
      }
    }
  }
</style>
